package com.itheima.reggie_test.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie_test.common.BaseContext;
import com.itheima.reggie_test.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ auther: 小熊
 * @ date:2022/12/14 15:15
 * @Todo :
 */

//登录检测过滤写完需在启动类上加上注解
    //   @ServletCompanenttScan

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    // url风格的匹配 ，需要用到一个类  AntPathMatcher antPathMatcher = new AntPathMatcher();  match方法
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 2.2 配置需要放行的地址【静态资源全部放 + 登录和退出的】：
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};

    // 判断 uri地址 是否 匹配 loginUrls其中之一
        //先对ServletRequest 进行强转(无获取URI的方法)
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取路径
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);

        //  /backend/**   匹配   uri:   /backend/index.html
        //比较路径
        Boolean check = check(requestURI,loginUrls);

        //不需要处理
        if (check){
            log.info("不需要处理:{}",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //需要进行登录的，判断登录状态
        if (request.getSession().getAttribute("empId")!=null){
            log.info("用户登录id为:{}",request.getSession().getAttribute("empId"));
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("empId"));
            filterChain.doFilter(request,response);
            return;
        }

        //移动端登录状态判断
        if (request.getSession().getAttribute("user")!=null){
            log.info("用户登录id为:{}",request.getSession().getAttribute("user"));
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }

        //未登录返回曾璐界面
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    //比较路径的方法
    private Boolean check(String uri, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }


}
